package com.xiaoxi.common.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Author xiaoxi
 * @ProjectName springcloudbms
 * @PackageName common.util
 * @ClassName ContextUtils
 * @Description TODO
 * @Date 2023/2/2 11:10
 * @Version 1.0
 */
public class ContextUtils {

    public static HttpServletRequest getHttpRequest() {
        return RequestContextHolder.getRequestAttributes() == null ? null : ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String getToken() {
        // 1. 从请求头获取token
        String token = getParamFromHeader(Objects.requireNonNull(getHttpRequest()));
        if (StringUtils.isEmpty(token)) {
            // 2. 从请求参数 token 参数
            token = getHttpRequest().getParameter(HttpHeaders.AUTHORIZATION);
        }
        if (StringUtils.isEmpty(token)) {
            return "";
        }
        return token;
    }

    public static String getRequestHeader(String headerName) {
        return Objects.requireNonNull(getHttpRequest()).getHeader(headerName);
    }

    private static String getParamFromHeader(HttpServletRequest request) {
        return request.getHeader(HttpHeaders.AUTHORIZATION);
    }

}
